<!-- 单点登录摇摆页 -->
<template>
    <div>

        <div style="height:100vh" class="flexCenter2">
            <img src="@/assets/login/authLoading.gif" alt="" style="width:600px;object-fit:contain">
        </div>


    </div>
</template>

<script >
import { codeLogin, checkToken } from '@/api/login.js'
import lazyRoute from '@/utils/menuLoad.js'
import { err404 } from '@/router/routerData.js'

export default {
    name: "",
    data() {
        return {
            spinning: true,
            projectId: 123,
            code: '',
            menuData: [

            ]
        }
    },
    mounted() {
        this.code = this.$route.query.code
        if (this.code) {
            this.apiCodeLogin()
        } else {

            //获取不到code参数，就回到登录页登录

            //获取当前地址
            let publicUrl =
                location.protocol +
                "//" +
                location.hostname +
                (location.port === 80 ? "" : ":" + location.port);
            //单点登录地址
            let authLoginUrl = window.authLoginUrl
            window.location = `${authLoginUrl}/oauth/authorize?client_id=HXJR&response_type=code&scope=HXJR&redirect_uri=${publicUrl}/auth`
        }
    },
    methods: {
        //通过code获取token
        apiCodeLogin() {
            const form = new FormData();
            form.append('code', this.code);

            codeLogin(form, this.projectId).then(res => {
                if (res.data.code === '1') {

                    sessionStorage.setItem('financial-token', JSON.stringify(res.data.data.tokenInfo))
                    //通过token获取用户信息和菜单
                    this.apiCheckToken()
                } else {
                    this.$message.destroy()
                    this.$message.error(res.data.msg)
                }
            }).catch(err => {
                console.log(err);
            })
        },
        //获取用户信息和菜单
        apiCheckToken() {
            const form = new FormData();
            let token = JSON.parse(sessionStorage.getItem('financial-token')).token
            form.append('token', token);
            form.append('clientId', 'financial_platform_clientId');

            checkToken(form, this.projectId).then(res => {
                if (res.data.code == '1') {
                    //菜单
                    // this.menuData = res.data.data.menuTree

                    this.menuData = [{
                        "title": "首页",
                        "value": "136",
                        "menuName": "首页",
                        "iconcls": "home",
                        "request": "home",
                        "parentId": "0",
                        "sortNo": 0,
                        "isEnable": 0,
                        "remark": "首页",
                        "key": "136",
                        "path": "/home",
                        "component": "home/home",
                        "hidden": false,
                        "children": []
                    },
                    {
                        "title": "工作流",
                        "value": "1364",
                        "menuName": "工作流",
                        "iconcls": "home",
                        "request": "bpmn",
                        "parentId": "1",
                        "sortNo": 0,
                        "isEnable": 0,
                        "remark": "工作流",
                        "key": "1365",
                        "path": "/bpmn",
                        "component": "bpmn/bpmn",
                        "hidden": false,
                        "children": []
                    },

                    ]

                    //用户信息
                    this.$store.dispatch('setUserInfo', res.data.data.userInfo)
                    this.authLogin()
                }
                else {
                    this.$message.destroy()
                    this.$message.error(res.data.msg)
                }
            }).catch(err => {
                console.log(err);
            })
        },
        //存储菜单，添加动态路由，跳进第一个菜单
        authLogin() {
            //递归过滤数据，如果是二级菜单，就要父的redirect等于第一个子菜单的path
            this.menuData = this.filterMenu(this.menuData)
            this.$store.commit('setMenuData', [])
            //存储菜单
            this.$store.commit('setMenuData', this.menuData)
            let routeData = JSON.parse(JSON.stringify(this.menuData))
            //由于页面要在基本布局里展示，所以每一层菜单外都要一层（component：'BasicLayout'）
            routeData.forEach(item => {
                if (item.component != 'BasicLayout') {
                    let children = JSON.parse(JSON.stringify(item))
                    item.children.push(children)
                    item.component = 'BasicLayout'
                    item.icon = item.iconcls
                }
            });
            // 递归过滤树,通过component字段找到文件目录对应的.vue文件
            let data = this.filterRoute(routeData)
            this.$store.commit('setRouterData', data)
            this.$router.addRoutes([...data, err404])
            let pathUrl = ''
            if (data[0].redirect) {
                pathUrl = data[0].redirect
            } else {
                pathUrl = data[0].path
            }
            console.log(pathUrl);
            //跳到第一个菜单
            this.$router.push({ path: pathUrl })
        },


        //递归过滤树,引入component文件
        filterRoute(treeArr) {
            function findItem(arr) {
                let res = arr.filter(item => {
                    if (item.children && item.children.length > 0) {
                        item.children = findItem(item.children)
                    }
                    item.component = lazyRoute(item.component)

                    return item
                })
                return res
            }
            return findItem(treeArr)
        },

        //递归过滤菜单
        filterMenu(treeArr) {
            function findItem(arr) {
                let res = arr.filter(item => {
                    if (item.children && item.children.length > 0) {
                        if (item.children[0].hidden != true) {
                            item.redirect = item.children[0].path
                        }
                        item.children = findItem(item.children)
                    }
                    return item
                })
                return res
            }
            return findItem(treeArr)
        },

    }
}
</script>

<style scoped>
::v-deep .ant-spin-nested-loading>div>.ant-spin {
    max-height: none;
}
</style>
